package com.getpebble.android.common.framework.install;

import com.getpebble.android.common.core.trace.Trace;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public abstract class PebbleBundle<M extends PebbleManifest> {
    public static final String TAG = PebbleBundle.class.getSimpleName();
    private Map<String, ZipEntry> mComponents;
    private ZipFile mFile;

    public abstract M getManifest();

    public PebbleBundle(ZipFile file, Map<String, ZipEntry> components) {
        if (file == null) {
            throw new IllegalArgumentException("'file' cannot be null!");
        } else if (components == null || components.isEmpty()) {
            throw new IllegalArgumentException("'components' cannot be null or empty!");
        } else {
            this.mFile = file;
            this.mComponents = components;
        }
    }

    protected Map<String, ZipEntry> getComponents() {
        return this.mComponents;
    }

    protected ZipFile getFile() {
        return this.mFile;
    }

    public InputStream getInputStreamForComponent(String componentName) throws IOException {
        if (((ZipEntry) getComponents().get(componentName)) != null) {
            return getFile().getInputStream((ZipEntry) getComponents().get(componentName));
        }
        throw new FileNotFoundException("Cannot find entry for " + componentName);
    }

    protected M parseManifest(Class<M> manifestClass) {
        M manifest = null;
        try {
            InputStream inputStream = getInputStreamForComponent("manifest.json");
            manifest = (PebbleManifest) new Gson().fromJson(new BufferedReader(new InputStreamReader(inputStream)), (Class) manifestClass);
            inputStream.close();
            return manifest;
        } catch (IOException ioe) {
            Trace.error(TAG, "Failed to parse manifest.", ioe);
            return manifest;
        }
    }

    public boolean hasResources() {
        return getManifest().getResourceInfo() != null;
    }

    public void closeFile() {
        try {
            this.mFile.close();
        } catch (IOException e) {
            Trace.debug(TAG, "Error closing file", e);
        }
    }
}
